package com.atguigu.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.DimSinkFunction;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

import java.util.Properties;

/**
 * @author Felix
 * @date 2023/12/16
 * 维度DIM层处理应用
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、hbase、DimApp
 * 开发流程
 *      环境准备
 *      检查点相关的设置
 *      从kafka主题中读取业务数据
 *      对流中的数据进行类型转换并进行简单的ETL    jsonStr->jsonObj
 *
 *      使用FlinkCDC读取配置表中的配置信息--配置流jsonStr
 *      将读取到的配置信息进行类型转换     jsonStr->TableProcess实体类对象
 *      根据配置表中配置信息提前到hbase中建表或者删表
 *
 *      广播配置流--broadcast
 *      将主流和广播流进行关联--connect
 *      对关联后的数据进行处理--process
 *          class TableProcessFunction extends BroadcastProcessFunction{
 *              open:将配置表中的配置信息预加载程序中
 *                  主要解决主流数据先到，配置表中的配置信息还没有放到广播状态的情况
 *              processElement:处理主流业务数据
 *                  根据处理的表名到广播状态中获取对应的配置信息
 *                  如果配置信息不为空说明是维度数据，向下游传递
 *                      过滤掉不需要传递的属性
 *                      补充type操作类型
 *                      补充维度表对应的配置信息
 *              processBroadcastElement:处理广播流配置信息
 *                  op="d":从广播状态中删除对应配置信息
 *                  op!="d":将配置信息更新到广播状态中
 *          }
 *      将维度数据写到Hbase中
 *          class DimSinkFunction{
 *              invoke:
 *                  type="delete":从hbase维度表中删除一条数据
 *                  type！="delete":向hbase维度表中添加一条数据
 *          }
 *  执行流程（以修改业务数据库品牌维度表中一条数据为例）
 *      当DimApp应用程序启动的时候，会将配置表中的配置信息加载程序中以及广播状态中
 *      当修改品牌维度后，binlog会将变化记录下来
 *      maxwell将变化读取到并封装为一个json格式字符串，发送到kafka的topic_db主题中
 *      DimApp应用，从kafka的topic_db主题中读取业务数据，并业务数据进行处理
 *      根据当前处理的业务数据库表的名称到广播状态以及configMap中获取对应的配置信息
 *      如果获取到了，说明是维度数据，传递到下游
 *      下游将维度流的数据写到Hbase
 */
public class DimApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*//TODO 2.检查点相关的设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/ck");
        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO 3.从kafka的主题中读取数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_db";
        String groupId = "dim_app_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);

        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaStrDS
            = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "Kafka Source");

        //TODO 4.对流中数据进行类型转换并进行简单的ETL    jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    //将jsonStr转换为jsonObj
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String type = jsonObj.getString("type");
                        if(!"bootstrap-start".equals(type)&&!"bootstrap-complete".equals(type)){
                            out.collect(jsonObj);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );

        // jsonObjDS.print(">>>>");

        //TODO 5.使用FlinkCDC从配置表中读取配置信息
        //5.1 创建MySqlSource
        Properties props = new Properties();
        props.setProperty("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop102")
            .port(3306)
            .databaseList("gmall0710_config") // set captured database
            .tableList("gmall0710_config.table_process_dim") // set captured table
            .username("root")
            .password("123456")
            .jdbcProperties(props)
            .serverTimeZone("Asia/Shanghai")
            .deserializer(new JsonDebeziumDeserializationSchema())
            .startupOptions(StartupOptions.initial())
            .build();

        //5.2 读取数据 封装为流
        DataStreamSource<String> mysqlStrDS
            = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysqlSource");
        //"op":"r": {"before":null,"after":{"source_table":"user_info","sink_table":"dim_user_info","sink_family":"info","sink_columns":"id,login_name,name,user_level,birthday,gender,create_time,operate_time","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0710_config","sequence":null,"table":"table_process_dim","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1702708358427,"transaction":null}
        //"op":"c": {"before":null,"after":{"source_table":"aa","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1702708446000,"snapshot":"false","db":"gmall0710_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11192547,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1702708446511,"transaction":null}
        //"op":"u"： {"before":{"source_table":"aa","sink_table":"dim_aaaa","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"after":{"source_table":"aa","sink_table":"dim_aaaa","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1702708498000,"snapshot":"false","db":"gmall0710_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11193304,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1702708498573,"transaction":null}
        //"op":"d"： {"before":{"source_table":"aa","sink_table":"dim_aaaa","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"after":null,"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1702708535000,"snapshot":"false","db":"gmall0710_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11193698,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1702708535743,"transaction":null}
        // mysqlStrDS.print(">>>");

        //TODO 6.将读取到每一条配置信息  封装为一个实体类对象
        SingleOutputStreamOperator<TableProcess> tableProcessDS = mysqlStrDS.map(
            new MapFunction<String, TableProcess>() {
                @Override
                public TableProcess map(String jsonStr) throws Exception {
                    //为了处理方便，将json字符串转换为json对象
                    JSONObject jsonObj = JSON.parseObject(jsonStr);
                    //获取操作类型
                    String op = jsonObj.getString("op");
                    TableProcess tableProcess = null;
                    if ("d".equals(op)) {
                        //说明从配置表中删除了一条数据  从before属性中获取删除前的配置表信息
                        tableProcess = jsonObj.getObject("before", TableProcess.class);
                    } else {
                        //c、r、u 都需要从after属性中获取配置表中的最新配置信息
                        tableProcess = jsonObj.getObject("after", TableProcess.class);
                    }
                    tableProcess.setOp(op);
                    return tableProcess;
                }
            }
        );

        // tableProcessDS.print(">>>");

        //TODO 7.根据配置信息  提前在Hbase中建表或者删表
        tableProcessDS = tableProcessDS.map(
            new RichMapFunction<TableProcess, TableProcess>() {
                private Connection hbaseConn;

                @Override
                public void open(Configuration parameters) throws Exception {
                    hbaseConn = HbaseUtil.getHbaseConnection();
                }

                @Override
                public void close() throws Exception {
                    HbaseUtil.closeHbaseConnection(hbaseConn);
                }

                @Override
                public TableProcess map(TableProcess tableProcess) throws Exception {
                    //获取对配置表进行的操作的类型
                    String op = tableProcess.getOp();
                    String sinkTable = tableProcess.getSinkTable();
                    String[] sinkFamilies = tableProcess.getSinkFamily().split(",");

                    if ("c".equals(op) || "r".equals(op)) {
                        //建表
                        HbaseUtil.createTable(hbaseConn, GmallConfig.HBASE_NAMESPACE, sinkTable, sinkFamilies);
                    } else if ("d".equals(op)) {
                        //删表
                        HbaseUtil.dropTable(hbaseConn, GmallConfig.HBASE_NAMESPACE, sinkTable);
                    } else {
                        //先删表
                        HbaseUtil.dropTable(hbaseConn, GmallConfig.HBASE_NAMESPACE, sinkTable);
                        //再建表
                        HbaseUtil.createTable(hbaseConn, GmallConfig.HBASE_NAMESPACE, sinkTable, sinkFamilies);
                    }
                    return tableProcess;
                }
            }
        );

        //TODO 8.广播配置流---broadcast
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
            = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);
        BroadcastStream<TableProcess> broadcastDS = tableProcessDS.broadcast(mapStateDescriptor);

        //TODO 9.将主流业务数据和广播流的配置数据进行关联---connect
        BroadcastConnectedStream<JSONObject, TableProcess> connectDS
            = jsonObjDS.connect(broadcastDS);

        //TODO 10.对关联后的数据进行处理---process(过滤出维度数据)
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
            new TableProcessFunction(mapStateDescriptor)
        );
        //TODO 11.将维度数据写到Hbase对应的维度表中
        //{"tm_name":"Redmi111","id":1,"type":"update",
        //"table_process":{"op":"r","sinkColumns":"id,tm_name","sinkFamily":"info","sinkRowKey":"id",
        //"sinkTable":"dim_base_trademark","sourceTable":"base_trademark"}}
        dimDS.print(">>>");
        dimDS.addSink(
            new DimSinkFunction()
        );



        env.execute();
    }
}
